package org.kernely.ui.mvp;
import java.util.ArrayList;

/**
 *  One unique general KernelyEventBusGeneral is created when the application is launched.
 *  The KernelyEventBusGeneral has reference on all the KernelyEventBus, in order to
 *  broadcast to all the presenters (not only the current user's presenters). This should
 *  be done only for major events, as adding a bundle or removing it from the application.
 *  See the event management on the wiki for more documentation.
 */
public class KernelyEventBusGeneral{
	
	private ArrayList<KernelyEventBus> busList;

	private static KernelyEventBusGeneral instance;
	
	// Singleton pattern
	private KernelyEventBusGeneral(){
		busList = new ArrayList<KernelyEventBus>();
	}
	
	/**
	 * Get the single instance of KernelyEventBusGeneral (singleton pattern)
	 * @return The instance of KernelyEventBusGeneral
	 */
	public static KernelyEventBusGeneral getInstance(){
		if (instance == null){
			instance = new KernelyEventBusGeneral();
		}
		return instance;
	}

	/**
	 *  Adds a registered event bus. Every KernelyEventBus should register to the KernelyEventBusGeneral.
	 *  @param The event bus to register.
	 */
	public synchronized void addEventBus(KernelyEventBus eventBus) {
		busList.add(eventBus);
	}
	
	/**
	 *  Removes a registered event bus. Every KernelyEventBus should unregister to the KernelyEventBusGeneral.
	 *  @param The event bus to unregister.
	 */
	public synchronized void removeEventBus(KernelyEventBus eventBus) {
		busList.remove(eventBus);
	}
	
	/**
	 * Broadcast an event to all the user's KernelyEventBus.
	 * @param The event to broadcast.
	 */
	@SuppressWarnings("unchecked")
	public synchronized void broadcastEvent(KernelyEvent event){
		if (event != null){
			ArrayList<KernelyEventBus> list = (ArrayList<KernelyEventBus>) busList.clone();
			for(KernelyEventBus bus : list){
				bus.broadcastEvent(event);
			}
		}
	}
}